package com.zbcz.crm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.BaseBean
import com.zbcz.crm.bean.Contacts
import com.zbcz.crm.bean.VisitData
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import com.zbcz.crm.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ContactsAddViewModel : ViewModel() {

    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)

    val mAddContactsResponse = MutableLiveData<Boolean>()

    fun addContacts(contacts: Contacts) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = addContactsSuspend(contacts)
            withContext(Dispatchers.Main) {
                if (result?.success == true) {
                    ToastUtils.show("添加成功")
                    mAddContactsResponse.postValue(true)
                } else {
                    result?.message?.let { ToastUtils.show(it) }
                    mAddContactsResponse.postValue(false)
                }
            }
        }
    }


    private suspend fun addContactsSuspend(contacts: Contacts): BaseBean<Object>? {
        try {
            return mApi.addContacts(
                token = SharedPreferencesManager.getToken(
                    CrmApplication.mApplication
                ),
                contacts
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}